﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ecommerce.Model
{
    public class CupomModel:BaseData
    {
        private static CupomModel instance;

        private CupomModel()
        {

        }

        public static CupomModel Instance
        {
            get
            {
                if (instance == null)
                    instance = new CupomModel();
                
                return instance;
            }
        }

        public List<tb_cup_cupom> Listar()
        {
            using (var db = new EcommerceEntities(this.InicializarStringConexao(), false))
                return db.tb_cup_cupom.OrderBy(x => x.cup_idt_cupom).ToList();
        }

        public tb_cup_cupom Obter(int identificador)
        {
            using (var db = new EcommerceEntities(this.InicializarStringConexao(), false))
                return db.tb_cup_cupom.Where(x => x.cup_idt_cupom == identificador).FirstOrDefault();
        }

        public tb_cup_cupom Inserir(tb_cup_cupom cupom)
        {
            var resultado = default(tb_cup_cupom);
            using (EcommerceEntities db = new EcommerceEntities(this.InicializarStringConexao(), false))
            {
                resultado = db.tb_cup_cupom.Add(cupom);
                db.SaveChanges();
            }

            return resultado;
        }

        public void AssociarRevenda(int identificadorRevenda)
        {
            using (EcommerceEntities db = new EcommerceEntities(this.InicializarStringConexao(), false))
            {
                //resultado = db.tb_cup_cupom.Add(cupom);
                //db.SaveChanges();
            }
        }


        public tb_cup_cupom ListarCupom(string codigo)
        {
            tb_cup_cupom item;
            using (EcommerceEntities db = new EcommerceEntities(this.InicializarStringConexao(), false))
            {
                item = db.tb_cup_cupom.Include("tb_ped_pedido").Where(x => x.cup_flg_cupom_ativo == true && DateTime.Now >= x.cup_dat_inicio_validade && DateTime.Now <= x.cup_dat_fim_validade && x.cup_cod_cupom == codigo).FirstOrDefault();

                if (item == null)
                    return null;

                if (item.cup_flg_permite_unico_uso && item.tb_ped_pedido != null)
                    return null;
            }
            return item;
        }
    }
}
